<?php

ini_set('display_errors', 'Off');
// 启动文件
require_once __DIR__ . '/../core/bootstrap.php';

// 程序配置
$conf = include CONF . '/conf.php';

// 控制器
$con = new \sc\Controller(__DIR__ . '/page');

// 帮助类
$hel = new \sc\Helper();

// 身份检查
$index = base64_encode('sem-cms_manager_index');
$index_session = $con->session->get($index);
$index_cookie = $con->request->cookie($index);
if (!empty($index_session)) {
    $account = $index_session;
} else if (!empty($index_cookie)) {
    $account = $index_cookie;
} else {
    $account = null;
}
header('Content-Type:text/html; charset=UTF-8');
if (null != $account) {
    $name = $con->db->table('user')->find('u_name')->where('u_account = ?', [base64_decode($account)])->one();

    if (!isset($name['u_name'])) {
        // 账号不存在
        $url = $hel->path().'/login.php';
        // 删除错误账号信息
	    $path = $con->request->server('REQUEST_URI');
	    $path = substr($path, 0, strrpos($path, '/'));
	    setcookie($index, '', 1, $path, $con->request->server('HTTP_HOST'), false, true);
	    $con->session->remove($index);
        // 提示信息
        $con->session->set('err', '请先登录');
        $con->redirect($url);
    } else {
        if (null == $index_session) {
            // SESSION未存储
            $con->session->set($index, $account);
        }
    }
} else {
    // 未存储账号
    $url = $hel->path() . '/login.php';
    // 提示信息
    $con->session->set('err', '请先登录');
    $con->redirect($url);
}

// 获取用户角色
$user_role = $con->db->table('user')->find('u_role')->where('u_account = ?', [base64_decode($account)])->one();
$user_role = $user_role ? explode(',', $user_role['u_role']) : [];

// 解析请求
$uri = explode('?', $con->request->server('REQUEST_URI'));
$uri = implode('?', array_map(function ($value) {
	return ltrim($value, '/');
}, $uri));
$parse = parse_url(ltrim(strrchr($uri, '/'), '/'));
if (isset($parse['query'])) {
    parse_str($parse['query'], $params);
    $query = '';
    if (isset($params['lang'])) {
        $query .= '?lang='.$params['lang'];
    }
    if (isset($params['type'])) {
        $connector = isset($params['lang']) ? '&' : '?';
        $query .= $connector.'type='.$params['type'];
    }
    $path = $parse['path'].$query;
    unset($params, $query);
} else {
    $path = $parse['path'];
}

// 获取授权角色
$need = $con->db->table('role')->find('id, r_prompt')->where('r_url = ?', [$path])->one();
if (!$need) {
    $need['id'] = 0;
    $need['r_prompt'] = '核心管理权限';
}

// 解析角色级别
$roles = $con->db->table('role')->find('id, pid, r_url, r_name')->all();
$sub_role = $hel->subTree($roles, $need['id']);
$sup_role = $hel->parentTree($roles, $need['id']);

// 权限检查
if (!in_array($parse['path'], ['', 'index.php', 'logout.php', 'main.php'])) {
    $flag = true;
    foreach ($sup_role as $role) {
        if (in_array($role['id'], $user_role)) {
            $flag = false;
            break;
        }
    }
    if (!empty($sub_role)) {
        if ($flag) {
            $flag = checkSubPermission($sub_role, $user_role);
        }
    }
    if ($flag) {
        die('对不起，您无'.$need['r_prompt'].'权限，访问被拒绝');
    }
}
unset($roles, $sub_role, $parse);

// 面包屑导航
$breadcrumb = '';
switch (count($sup_role)) {
    case 4:
        $breadcrumb .= '<a href="javascript:top.location.href=\''.$hel->path().'/\'"><img src="'.$hel->path().'/img/home.png">'.$sup_role[3]['r_name'].'</a>';
        $breadcrumb .= '&raquo;<a href="'.$sup_role[2]['r_url'].'">'.$sup_role[2]['r_name'].'</a>';
        $breadcrumb .= '&raquo;<a href="javascript:parent.location.href=\''.$hel->path().'/'.$sup_role[1]['r_url'].'\'">'.$sup_role[1]['r_name'].'</a>';
        $breadcrumb .= '&raquo;<a href="'.$hel->path().'/'.$sup_role[0]['r_url'].'">'.$sup_role[0]['r_name'].'</a>';
        break;
    case 1:
        $breadcrumb .= '<a href="'.$hel->path().'/'.$sup_role[0]['r_url'].'">'.$sup_role[0]['r_name'].'</a>';
        break;
    case 2:
        $breadcrumb .= '<a href="'.$sup_role[1]['r_url'].'"><img src="'.$hel->path().'/img/home.png">'.$sup_role[1]['r_name'].'</a>';
        $breadcrumb .= '&raquo;<a href="'.$hel->path().'/'.$sup_role[0]['r_url'].'">'.$sup_role[0]['r_name'].'</a>';
        break;
    case 3:
        $breadcrumb .= '<a href="'.$hel->path().'/'.$sup_role[2]['r_url'].'"><img src="'.$hel->path().'/img/home.png">'.$sup_role[2]['r_name'].'</a>';
        $breadcrumb .= '&raquo;<a href="'.$sup_role[1]['r_url'].'">'.$sup_role[1]['r_name'].'</a>';
        $breadcrumb .= '&raquo;<a href="'.$hel->path().'/'.$sup_role[0]['r_url'].'">'.$sup_role[0]['r_name'].'</a>';
        break;
    default:break;
}
unset($sup_role);

// 版本号
$version = '1.0.0';

/**
 * 检查子级权限
 *
 * @param array $sub_role
 * @param array $user_role
 *
 * @return bool
 */
function checkSubPermission($sub_role, $user_role)
{
    $flag = true;
    foreach ($sub_role as $s) {
        if (in_array($s['id'], $user_role)) {
            $flag = false;
            break;
        }
        if (isset($s['sub'])) {
            $flag = checkSubPermission($s['sub'], $user_role);
        }
    }

    return $flag;
}

/**
 * 加载图片
 *
 * @param string     $image
 * @param \sc\Helper $hel
 *
 * @return string
 */
function loadImage($image, $hel, $host = true) {
    if (!is_file(PATH.'/'.trim($image, '/'))) {
        $image = 'file/w.gif';
    }
    if ($host) {
        return $hel->to($image);
    }
    return $image;
}
